package com.eastshop.product.dao;

import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.eastshop.product.vo.Product;
import com.eastshop.utils.PageHibernateCallback;
/**
 * 商品的Dao层代码
 * @author admin
 *
 */
public class ProductDao extends HibernateDaoSupport {
	// Dao层根据分类id查找商品
	public List<Product> findByCid(Integer cid) {
		String hql = "from Product p where p.category.cid = ? order by pdate desc";
		Query query = this.getSession().createQuery(hql);
		query.setParameter(0, cid);
		query.setFirstResult(0); // 开始记录
		query.setMaxResults(10); // 查询出来的记录
		List<Product> list = query.list();
		if(list != null && list.size() > 0){
			return list;
		}
		return null;
	}
	
	// Dao层根据分类的id查找商品数量
	public int findCountByCid(Integer cid) {
		String hql = "select count(*) from Product p where p.category.cid = ?";
		List<Long> list = this.getHibernateTemplate().find(hql, cid);
		if(list != null && list.size() > 0){
			return list.get(0).intValue();
		}
		return 0;
	}
	
	// Dao层根据分类的id分页查询商品
	public List<Product> findByCidWithPage(Integer cid, int begin, int limit) {
		String hql = "from Product p where p.category.cid = ?";
		List<Product> list = this.getHibernateTemplate().execute(new PageHibernateCallback<Product>(hql, new Object[]{cid}, begin, limit));
		if(list != null && list.size() > 0){
			return list;
		}
		return null;
	}

	// Dao层根据商品的id查询商品
	public Product findByPid(Integer pid) {
		Product product = this.getHibernateTemplate().get(Product.class, pid);
		return product;
	}

	// Dao层查找商品的数量
	public int findCount() {
		String hql = "select count(*) from Product";
		List<Long> list = this.getHibernateTemplate().find(hql);
		if(list != null && list.size() > 0){
			return list.get(0).intValue();
		}
		return 0;
	}

	// Dao层分页查询商品信息
	public List<Product> findAllWithPage(int begin, int limit) {
		String hql = "from Product order by pdate desc";
		List<Product> list = this.getHibernateTemplate().execute(new PageHibernateCallback<Product>(hql, null, begin, limit));
		if(list != null && list.size() > 0){
			return list;
		}
		return null;
	}

	// Dao层删除商品的方法
	public void delete(Product product) {
		this.getHibernateTemplate().delete(product);
	}

	// Dao层保存商品信息
	public void save(Product product) {
		this.getHibernateTemplate().save(product);
	}

	// Service层更新商品信息
	public void update(Product product) {
		this.getHibernateTemplate().update(product);
	}

}
